﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace SocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 2000;
            string host = "127.0.0.1";

            IPAddress ip = IPAddress.Parse(host);

            IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和IP初始化IPEndPoint类的新实例
            //创建一个Socket对象，如果用udp协议，则要用SocketType.Dgram类型的套接字
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(ipe);//绑定EndPoint对象
            s.Listen(0);//开始监听Socket
            Console.WriteLine("等待客户端连接");

            /*接收到client端连接，为此连接建立新的Socket，并接收信息*/
            Socket temp = s.Accept();//为新建连接创建新的Socket

            Console.WriteLine("建立连接");

            string recvStr = string.Empty;
            byte[] recvBytes=new byte[1024];
            int bytes = temp.Receive(recvBytes, recvBytes.Length, 0);
            recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

            /*给客户端返回信息*/

            Console.WriteLine("server get message:{0}", recvStr);//把客户端传来的信息显示出来

            string sendStr = "ok!Client send message successful!";

            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            temp.Send(bs, bs.Length, 0);
            temp.Close();

            s.Close();

            Console.ReadLine();
        }
    }
}
